package com.twang.stock.task;

import com.alibaba.fastjson.JSONObject;
import com.twang.stock.common.http.HtmlTools;
import com.twang.stock.dto.DataObject;
import com.twang.stock.dto.EmailMessage;
import com.twang.stock.dto.StockMinutesMessage;
import com.twang.stock.entity.CompanyCodeInfo;
import com.twang.stock.entity.CompanyStockMinutes;
import com.twang.stock.entity.WenCaiData;
import com.twang.stock.mapper.CompanyCodeInfoMapper;
import com.twang.stock.mapper.CompanyStockMinutesMapper;
import com.twang.stock.mapper.WenCaiDataMapper;
import com.twang.stock.redis.RedisUtil;
import com.twang.stock.rocketMq.RocketMQProducer;
import com.twang.stock.service.jinyan.CommonService;
import com.twang.stock.service.jinyan.UpdateStockCoreService;

import com.twang.stock.task.old.BaseTask;
import com.twang.stock.threadPool.AsycTaskExecutorConfig;
import com.twang.stock.utils.date.HolidayCopy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 复盘提醒
 */
@Slf4j
@Component
public class MinutesStockFixTask extends BaseTask {


    @Autowired
    private AsycTaskExecutorConfig asycTaskExecutorConfig;

    @Resource
    private CompanyCodeInfoMapper companyCodeInfoMapper;

    @Resource
    private CompanyStockMinutesMapper companyStockMinutesMapper;

    @Autowired
    private RedisUtil redisUtil;

     @Autowired
    private RocketMQProducer rocketMQProducer;


    @Autowired
    private UpdateStockCoreService updateStockCoreService;

    @Resource
    private WenCaiDataMapper wenCaiDataMapper;

    @Autowired
    private CommonService commonService;

    private static String COMPANY_STOCK_CODE_LIST = "COMPANY_STOCK_CODE_LIST_";



    @Scheduled(cron = "0 05 15 * * ?")
    public void excute() throws Exception {
        if (!isWork()) {
            return;
        }
        asycTaskExecutorConfig.taskQueueExecutor().execute(() -> {
            try {
                //开始修正数据
                initMinutesDataNew();
                //更新股票池
                updateStockCoreService.updateCore(1);
                //更新今天的A股涨幅榜单：今年涨幅前20个股
                //年度涨幅榜更新();
            } catch (Exception e) {
                log.info("error = {}", e);
            }
            log.info("==========> 消息刷新  TodayReDuOnehourTask end!");
        });



    }

    public void 年度涨幅榜更新() throws Exception {
        List<DataObject> dataObjects = QueryBanKuaiAndDaPan.今年涨幅前20个股();
        for (int i = 0; i < dataObjects.size(); i++) {
            DataObject item = dataObjects.get(i);
            String code=item.getCode();
            if (code.startsWith("8")||code.startsWith("2")||code.startsWith("4")) {
                continue;
            }
            WenCaiData wenCaiData = new WenCaiData();
            BeanUtils.copyProperties(item, wenCaiData);
            WenCaiData param = new WenCaiData();
            param.setCode(wenCaiData.getCode());
            List<WenCaiData> wenCaiData1 = wenCaiDataMapper.select(param);
            if (CollectionUtils.isEmpty(wenCaiData1)) {
                StringBuffer content = new StringBuffer();
                content.append("<div style='margin-left:4%;font-size:15px;'>");
                content.append("有一只新股票进入年度涨幅前20了：");
                content.append("<a style='color:dark;' href=\"http://stock520.cn/stockKanDian?code=").append(wenCaiData.getCode()).append("\">").append(wenCaiData.getStockName()).append("</a>");
                {
                    content.append("<p style='color:red;font-size:30px;'>");
                    content.append("区间涨幅：").append(item.getChangeRate()).append("%");
                    content.append("<br>");
                    content.append("</p>");
                }
                content.append("</div>");
                EmailMessage emailMessage = new EmailMessage();
                emailMessage.setCode("000001");
                emailMessage.setName("年度新晋涨幅榜");
                emailMessage.setMessage(content.toString());
                emailMessage.setType("1");
                List<String> ids = Arrays.asList(commonService.getValue("warn_ID").toString().split(","));
                for (String id : ids) {
                    emailMessage.setUserId(Long.valueOf(id));
                    log.info(">>>>>>>>>>> 年度新晋涨幅榜 emailMessage={}", JSONObject.toJSONString(emailMessage));
                     rocketMQProducer.sendOneWay(JSONObject.toJSONString(emailMessage));
                }
                wenCaiData.setChangeRank(i+1);
                wenCaiDataMapper.insert(wenCaiData);
            }else{
                wenCaiData.setId(wenCaiData1.get(0).getId());
                wenCaiDataMapper.updateByPrimaryKey(wenCaiData);
            }

        }
    }

    public void initMinutesDataNew() throws InterruptedException {
        List<String> dates = companyStockMinutesMapper.queryDates();
        String date = dates.get(dates.size() - 1);
        try {
            List<CompanyCodeInfo> list;
            Object object = redisUtil.get(COMPANY_STOCK_CODE_LIST + date);
            if (null != object) {
                list = (List<CompanyCodeInfo>) object;
            } else {
                list = companyCodeInfoMapper.selectAll();
                redisUtil.set(COMPANY_STOCK_CODE_LIST + HolidayCopy.getRealToday(), list);
            }
            List<CompanyCodeInfo> list1 = list.stream().filter(item -> !(item.getShortName().contains("退") || item.getShortName().contains("B") || item.getShortName().contains("*ST") || item.getShortName().contains("ST") || item.getShortName().contains("*"))).collect(Collectors.toList());
            StringBuffer code = new StringBuffer("");
            int i = 0;
            for (CompanyCodeInfo companyCodeInfo : list1) {
                if (i < 100) {
                    code.append(companyCodeInfo.getCompanyCode()).append(",");
                } else {
                    i=0;
                    String finalCode = code.toString();
                    asycTaskExecutorConfig.taskQueueExecutor().execute(() -> {
                        try {
                            covertDTO(finalCode,date);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    });
                    code = new StringBuffer("");
                    code.append(companyCodeInfo.getCompanyCode()).append(",");
                }
                i++;
            }
            covertDTO(code.toString(),date);
        } catch (Exception e) {
           log.info("error : e",e);
        }
    }

    /**
     *
     * @param code
     * @throws InterruptedException
     */
    private void covertDTO(String code,String date) throws InterruptedException {
        StockMinutesMessage message = new StockMinutesMessage();
        //message.setMinutes(HolidayCopy.getHHmmss().substring(8, 12));
        message.setDate(date);
        message.setType(StockMinutesMessage.TYPE_MINUTES_FIX);
        message.setCode(code);
        log.info(">>>>>>>>>>>> covertDTO  message={}",JSONObject.toJSONString(message));
        rocketMQProducer.sendOneWay(JSONObject.toJSONString(message));
    }

        public void initMinutesData(String date) {
        try {
            List<CompanyCodeInfo> list  = getCompanyCodeInfos();
            List<CompanyCodeInfo> list1 = list.stream().filter(item -> !(item.getShortName().contains("退") || item.getShortName().contains("B") || item.getShortName().contains("*ST") || item.getShortName().contains("ST") || item.getShortName().contains("*"))).collect(Collectors.toList());
            /**
             * map迭代
             */
            for (CompanyCodeInfo item : list1) {
                asycTaskExecutorConfig.taskQueueExecutor().execute(() -> {
                    log.info(JSONObject.toJSONString(item));
                    if (item.getShortName().contains("退") || item.getShortName().contains("B") || item.getShortName().contains("*ST") || item.getShortName().contains("ST") || item.getShortName().contains("*")) {
                        return;
                    }
                    getZDT(item.getCompanyCode(), item.getShortName(),date);
                    //rocketMQProducer.sendOneWay(item.getCompanyCode()+"-"+HolidayCopy.getHHmmss().substring(8, 12));
                });
            }
        } catch (Exception e) {
            throw e;
        }
    }

    public List<CompanyCodeInfo> getCompanyCodeInfos() {
        List<CompanyCodeInfo> list;
        Object object = redisUtil.get(COMPANY_STOCK_CODE_LIST + HolidayCopy.getRealToday());
        if (null != object) {
            list = (List<CompanyCodeInfo>) object;
        } else {
            list = companyCodeInfoMapper.selectAll();
            redisUtil.set(COMPANY_STOCK_CODE_LIST + HolidayCopy.getRealToday(), list);
        }
        return list;
    }

    public void getZDT(String code, String name,String dateTemp) {
        log.info(">>>>>>>>> code={}  name={}  start", code, name);
        List<String> dataList = HtmlTools.httpTenXun(code);
        String result = dataList.get(0);
        List<String> strings = JSONObject.parseArray(result, String.class);
        if(strings.size()<200){
            return;
        }
        BigDecimal yesterDayPrice=BigDecimal.ZERO;
        List<CompanyStockMinutes> insert= Lists.newArrayList();
        for (int i = 0; i < strings.size(); i++) {
            try {
                String[] data = strings.get(i).split(" ");
                //
                CompanyStockMinutes temp = new CompanyStockMinutes();
                if(StringUtils.isNotEmpty(dateTemp)){
                    temp.setDate(dateTemp);
                }else{
                    temp.setDate(HolidayCopy.getRealToday());
                }
                //temp.setDate("20230614");
                temp.setCompanyCode(code);
                if ((data[0].startsWith("15"))&&!"1500".equals(data[0])) {
                    continue;
                } else {
                    temp.setMinutes(data[0]);
                }
                    companyStockMinutesMapper.delete(temp);
                    CompanyStockMinutes companyStockMinutes = new CompanyStockMinutes();
                    companyStockMinutes.setCompanyCode(code);
                    companyStockMinutes.setCompanyName(name);
                    companyStockMinutes.setMinutes(temp.getMinutes());
                    companyStockMinutes.setDate(temp.getDate());
                    companyStockMinutes.setPrice(new BigDecimal(data[1]));
                    companyStockMinutes.setTradeVol(new BigDecimal(data[2]));
                    companyStockMinutes.setTradeSum(new BigDecimal(data[3]));
                    companyStockMinutes.setCreateTime(new Date());
                    if (i == 0) {
                        companyStockMinutes.setVol(new BigDecimal(data[2]));
                        companyStockMinutes.setAmount(new BigDecimal(data[3]));
                        List<String> dates = companyStockMinutesMapper.queryDates();
                        /** 昨天 */
                        String date = dates.get(dates.size() - 2);
                       List<CompanyStockMinutes> companyStockMinutesList=companyStockMinutesMapper.queryYesterDayInfo(companyStockMinutes.getCompanyCode(),date);
                       if(CollectionUtils.isNotEmpty(companyStockMinutesList)){
                           yesterDayPrice=companyStockMinutesList.get(0).getPrice();
                       }
                        companyStockMinutes.setZhangDie((companyStockMinutes.getPrice().subtract(yesterDayPrice).divide(yesterDayPrice,4,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100))));
                    } else {
                        if("1300".equals(temp.getMinutes())){
                            temp.setMinutes("1130");
                        }else{
                            temp.setMinutes(calculatePreviousMinute(temp.getMinutes()));
                        }
                        List<CompanyStockMinutes>  companyStockMinutesList=companyStockMinutesMapper.select(temp);
                        if (CollectionUtils.isNotEmpty(companyStockMinutesList)) {
                            CompanyStockMinutes last= companyStockMinutesList.get(0);
                            companyStockMinutes.setZhangDie((companyStockMinutes.getPrice().subtract(yesterDayPrice).divide(yesterDayPrice,4,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100))));
                            companyStockMinutes.setVol(companyStockMinutes.getTradeVol().subtract(last.getTradeVol()));
                            companyStockMinutes.setAmount(companyStockMinutes.getTradeSum().subtract(last.getTradeSum()));
                        }else{
                            log.info(">>>>>>>>>>> 为查询到 data={} ",data);
                        }
                    }
                    //
                    if("1500".equals(companyStockMinutes.getMinutes())){
                        companyStockMinutes.setZhangDie(HtmlTools.httpGet("s_"+code).get(0).getPriceChangePercentage());
                    }
                    //companyStockMinutesMapper.insert(companyStockMinutes);
                insert.add(companyStockMinutes);
            } catch (Exception e) {
                log.error(">>>>>> str={} error={}", strings.get(i), e);
                throw e;
            }
        }
        log.info(">>>>>>>>> code={}  name={}  end size={}", code, name, strings.size());
    }

    public static String calculatePreviousMinute(String currentTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmm");
        LocalTime time = LocalTime.parse(currentTime, formatter);
        LocalTime previousMinute = time.minusMinutes(1);
        return previousMinute.format(formatter);
    }

}
